<script setup>
import { defineComponent, h, markRaw } from "vue";
import FormPopup from "./FormPopup.vue";

// 2. 组件映射（支持多个自定义组件）
const componentMap = {
  formpopup: markRaw(FormPopup)
};

// 3. 解析 HTML 并渲染组件
const DynamicRenderer = defineComponent({
  props: {
    html: String
  },
  render() {
    const parser = new DOMParser();
    const doc = parser.parseFromString(this.html, "text/html");

    const traverse = node => {
      if (node.nodeType === Node.TEXT_NODE) {
        return node.textContent;
      }

      if (node.nodeType === Node.ELEMENT_NODE) {
        const tag = node.tagName.toLowerCase();
        if (componentMap[tag]) {
          const props = {};
          // 获取元素的所有属性并传递给组件
          [...node.attributes].forEach(attr => {
            props[attr.name] = node.getAttribute(attr.name);
          });
          console.log(props);
          return h(componentMap[tag], props, node.innerHTML);
        }

        return h(
          tag,
          Object.fromEntries([...node.attributes].map(attr => [attr.name, attr.value])),
          [...node.childNodes].map(traverse)
        );
      }
    };

    return h("div", {}, [...doc.body.childNodes].map(traverse));
  }
});

defineProps({
  html: {
    type: String,
    default: ""
  }
});

const keywords = ["formpopup", "custombutton"];

// 匹配关键字
const matchKeyWords = str => {
  // 判断props.html是否包含关键字数组
  return keywords.some(keyword => str.includes(keyword));
};
</script>

<template>
  <div
    v-if="!matchKeyWords(html)"
    v-html="html"
  ></div>
  <DynamicRenderer
    :html="html"
    v-else
  />
</template>
